import base64
import json

import requests
import urllib3
import uuid
import xlsxwriter

urllib3.disable_warnings()


class PanbaiduSpider:
    def __init__(self, start_dir, token):
        self.start_dir = start_dir
        self.token = token
        self.headers = {
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36",
            "Cookie": "BAIDUID=7D798A834B031016C191F9CAD97709E4:FG=1; PSTM=1562312797; BIDUPSID=03585E0B9B2473ADA90F0BB45D957A45; PANWEB=1; BDUSS=W4taWNENG13SjJlNTJFRFJLekZtRUJ-alprMlUxMHJiMGVXcUVpaWQwdHJnSkJkRVFBQUFBJCQAAAAAAAAAAAEAAAAAaZDxvq7DtzA3MDkAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAGvzaF1r82hdQ; SCRC=8c87f085b1ab42c435bda5a2cdff2df2; MCITY=-131%3A; BDCLND=2dkkAt3clELnyPp6Z5bprCnlDSBYLic5; __51cke__=; Hm_lvt_7a3960b6f067eb0085b7f96ff5e660b0=1567753975,1567999461,1567999623,1568097962; H_PS_PSSID=; BDORZ=FFFB88E999055A3F8A630C64834BD6D0; BDSFRCVID=3F_OJeC62mB6TCOwqIS4u_IyHe0dbAjTH6aouiR9fB4AG2pvPa6QEG0Pex8g0KubKoHFogKK0mOTHv8F_2uxOjjg8UtVJeC6EG0P3J; H_BDCLCKID_SF=tJA8oC_yfCI3fP36qROq-tuVMqO02-CXKKOLVhKX0h7keq8CD6DVyJk95lJhQMIDKJnGK-O4-PQ2VPQ2y5jHhTkRytr3Wx7GL2jf0-OO5M7psIJMy-DWbT8U5f5i2MvlaKviaKJEBMb1SJvDBT5h2M4qMxtOLR3pWDTm_q5TtUt5OCF4j5Dhj6oWDNRb5K6yaDTesJjVf56TOq7_bf--DR-YM-6utRbhLKcJ3DbP3-OCq-Qx0njxy5K_hPnae6br3mrNQlKXtRL-s4THQT3mbqQbbN3i-4ja3g5-Wb3cWKJV8UbS3tRPBTD02-nBat-OQ6npaJ5nJq5nhMtRy6CKj550jGLfJ5nbK-oyWJ5bHJjEbpQueMnkbfJBDlJGaUTuJ6vh-t3zKDbIsPO-Kbj20nK7yajK2MRaHRvrKlo4-lKBhJLCQRrpQT8rbJ_OK5OibCraKpTHab3vOIJzXpO13tPzBN5thURB2DkO-4bCWJ5TMl5jDh05y6TXjaDttj_ftb3yWJ5bHJjEbn8CQxnkbfJBDGruBq3jLjvDaR79bx7zJqnE0qnAM5L7yajK2bOEL5AJ0fOa5tOJhJLC24cpQT8rQMDOK5Oi0CraKpTHab3vOIJzXpO156kzBN5thURB2DkO-4bCWJ5TMl5jDh05y6TXDNuDJjk8fR3fL-08bn5HDJoY5-rohCCShUFsJM5dB2Q-5KL-al_-ShOO5nQz0T00BPr8BPLj5IrCBfbdJJjofJT-etjIjM_1Dl3qQP_qLmTxoUJHMInJhhvG-xRoyMKebPRiJPr9QgbqVpQ7tt5W8ncFbT7l5hKpbt-q0x-jLn7ZVJO-KKCabDI6jMK; STOKEN=3189e792a4cce7744cf90ee06a43cb2e4ed7715d0c96c36b4507fff518e2ff1a; delPer=0; PSINO=2; __tins__19988117=%7B%22sid%22%3A%201568619236935%2C%20%22vd%22%3A%201%2C%20%22expires%22%3A%201568621036935%7D; __51laig__=49; Hm_lpvt_7a3960b6f067eb0085b7f96ff5e660b0=1568619237; cflag=13%3A3; PANPSC=112394276154942429%3AKkwrx6t0uHAsCsd43XGHsEy7txDAjOFZ%2B2dhcLwhI8sMO5Yj42p4VigfkNTWN%2FRKmldUB8t5cdvZxB3ILlGMkvEZy5xVYxZqLvxjdeGWe17jGnhAWNtUtbuIldfEW52AY8uG8AM%2BY0Ih6uZoP3DwQ3ePlzJEAU4t4oRCM5jrTJ0BDChpkEtqiw%3D%3D"
        }

    def assemble_url(self, dir, token, log_id):
        url = "https://pan.baidu.com/api/list?dir={}&bdstoken={}&logid={}==&order=size&desc=0&clienttype=0&showempty=0&web=1&channel=chunlei&appid=286652".format(
            dir, token, log_id)
        return url

    def parse_url(self, url):
        resp = requests.get(url, headers=self.headers, verify=False)
        return json.loads(resp.content.decode())

    def get_log_id(self):
        bs64 = base64.b64encode(str(uuid.uuid1()).encode('utf-8')).decode()
        return bs64

    def get_file_list(self, dir, token, log_id, file_list=[]):
        url = self.assemble_url(dir, token, log_id)
        content_list = self.parse_url(url).get('list')
        if content_list:
            for content in content_list:
                if content['isdir'] == False:
                    file_list.append(content['path'].split(self.start_dir)[-1].split('/')[1:])
                    print(content['path'].split(self.start_dir)[-1].split('/')[1:])
                else:
                    log_id = self.get_log_id()
                    next_dir = content['path']
                    self.get_file_list(next_dir, token, log_id, file_list)
            return file_list

    def run(self):
        logid = self.get_log_id()
        file_list = self.get_file_list(self.start_dir, token, logid)
        f = xlsxwriter.Workbook('panbaidu_file.xlsx')  # 创建excel文件
        worksheet = f.add_worksheet('file')  # 括号内为工作表表名
        for row in range(len(file_list)):
            for column in range(len(file_list[row])):
                worksheet.write(row, column, file_list[row][column])
        f.close()


if __name__ == '__main__':
    dir = "/apps/bypy/电子书籍"
    token = "c3704a777c724f61a3b0da874bc875e9"
    xunbo = PanbaiduSpider(dir, token)
    xunbo.run()
